from flask import Blueprint, request, jsonify
import pandas as pd
from datetime import datetime
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import base64
from ..models import SelfFillform
from ..base import base
from .. import  db
from flask import send_file
from io import BytesIO
from .analysis import appRegisterMcpTool

# SM4加密密钥
SM4_KEY = b'0123456789abcdef'  # 替换为你的实际密钥
SM4_IV = b'abcdef0123456789'   # 替换为你的实际IV

def sm4_encrypt(data: str) -> str:
    """SM4加密方法"""
    cipher = AES.new(SM4_KEY, AES.MODE_CBC, SM4_IV)
    padded_data = pad(data.encode('utf-8'), AES.block_size)
    encrypted = cipher.encrypt(padded_data)
    return base64.b64encode(encrypted).decode('utf-8')

def sm4_decrypt(encrypted_data: str) -> str:
    """SM4解密方法"""
    cipher = AES.new(SM4_KEY, AES.MODE_CBC, SM4_IV)
    encrypted_bytes = base64.b64decode(encrypted_data)
    decrypted = cipher.decrypt(encrypted_bytes)
    return unpad(decrypted, AES.block_size).decode('utf-8')

@base.route('/smart/fillform/upload', methods=['POST'])
def upload():
    if 'file' not in request.files:
        return jsonify({'error': 'No file uploaded'}), 400
    
    file = request.files['file']
    task_name = request.form.get('task_name', '')
    login_user = request.form.get('login_user', '')
    login_pwd = request.form.get('login_pwd', '')
    
    if not file.filename.endswith(('.xlsx', '.xls')):
        return jsonify({'error': 'Invalid file type'}), 400
    
    try:
        # appRegisterMcpTool.main(file,login_user,login_pwd);
        file.seek(0)
        # 读取Excel文件并验证
        df = pd.read_excel(file)
        
        required_fields = ['*应用/微应用描述', '*应用级别', '*业务部门联系人',
                          '*业务部门联系方式', '*承建厂商', '*厂商联系方式', '主依赖中台']
        for field in required_fields:
            if field not in df.columns:
                return jsonify({'error': f'缺少必填字段: {field}'}), 400
        
        # 加密密码
        encrypted_pwd = sm4_encrypt(login_pwd)
        
        # 保存到数据库
        new_task = SelfFillform(
            task_name=task_name,
            excel=file.read(),
            login_user=login_user,
            login_pwd=encrypted_pwd,
            create_date=datetime.now(),
            exec_status='成功'
        )
        db.session.add(new_task)
        db.session.commit()
        
        # 返回最新任务列表
        tasks = SelfFillform.query.order_by(SelfFillform.id.desc()).all()
        history = [{
            'task_name': t.task_name,
            'login_user': t.login_user,
            'create_date': t.create_date.strftime('%Y-%m-%d %H:%M:%S'),
            'exec_status': t.exec_status
        } for t in tasks]
        
        return jsonify({'data': history})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@base.route('/smart/fillform/list', methods=['GET'])
def list_tasks():
    page = request.args.get('page', 1, type=int)
    limit = request.args.get('limit', 20, type=int)
    
    query = SelfFillform.query.order_by(SelfFillform.id.desc())
    pagination = query.paginate(page=page, per_page=limit, error_out=False)
    
    history = [{
        'id': t.id,
        'task_name': t.task_name,
        'login_user': t.login_user,
        'create_date': t.create_date.strftime('%Y-%m-%d %H:%M:%S'),
        'exec_status': t.exec_status
    } for t in pagination.items]
    
    return jsonify({
        'data': history,
        'total': pagination.total
    })


@base.route('/smart/fillform/detail/<int:task_id>', methods=['GET'])
def get_task_detail(task_id):
    task = SelfFillform.query.get(task_id)
    if not task:
        return jsonify({'error': 'Task not found'}), 404
    
    return jsonify({
        'id': task.id,
        'task_name': task.task_name,
        'login_user': task.login_user,
        'create_date': task.create_date.strftime('%Y-%m-%d %H:%M:%S'),
        'exec_status': task.exec_status,
        'excel': base64.b64encode(task.excel).decode('utf-8') if task.excel else None
    })


@base.route('/smart/fillform/download/<int:task_id>', methods=['GET'])
def download_excel(task_id):
    try:
        # 从数据库获取任务记录
        task = SelfFillform.query.get_or_404(task_id)
        
        if not task.excel:
            return {'message': 'Excel文件不存在'}, 404
            
        # 创建文件流
        file_stream = BytesIO(task.excel)
        
        # 返回文件下载
        return send_file(
            file_stream,
            as_attachment=True,
            download_name=f'{task.task_name}.xlsx',
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )
    except Exception as e:
        return {'message': f'下载失败: {str(e)}'}, 500


@base.route('/smart/fillform/delete/<int:id>', methods=['DELETE'])
def delete_fillform(id):
    try:
        record = SelfFillform.query.get_or_404(id)
        db.session.delete(record)
        db.session.commit()
        return jsonify({'code': 200, 'message': '删除成功'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'code': 500, 'message': f'删除失败: {str(e)}'})